import { Router } from '@angular/router';
import { BirefApiService } from './../../../api/biref-api.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { BriefAdderComponent } from './../../../common-util/brief-adder/brief-adder.component';
import { PeroidicTaskAdderComponent } from './../peroidic-task-adder/peroidic-task-adder.component';
import { PeriodicTask, PeriodicTaskParam, ProcessStatus } from './../../../model/task';
import { FormGroup, FormBuilder } from '@angular/forms';
import { Component, OnInit, ViewChild } from '@angular/core';
import { PeriodTaskApiService } from 'src/app/api/period-task-api.service';

@Component({
  selector: 'app-peroidic-task-overview',
  templateUrl: './peroidic-task-overview.component.html',
  styleUrls: ['./peroidic-task-overview.component.less']
})
export class PeroidicTaskOverviewComponent implements OnInit {
  searchFrom: FormGroup;
  taskList: Array<PeriodicTask> = [];
  isTaskModalVisible = false;
  taskModalTitle = '添加工作';
  isTaskBriefVisible = false;
  @ViewChild('taskAdder') taskAdder?: PeroidicTaskAdderComponent;
  @ViewChild('briefAdder') breidAdder?: BriefAdderComponent;
  isTableLoding = false;

  constructor(
    private fb: FormBuilder,
    private taskApi: PeriodTaskApiService,
    private msg: NzMessageService,
    private briefApi: BirefApiService,
    private router: Router
  ) {
    this.searchFrom = fb.group({
      name: [],
      target: [],
      tags: [],
      processStatus: [],
      importance: [],
      periodEndTime: [],
      end: [],
      prevStatus: []
    });
  }

  ngOnInit(): void {
    this.fetchData();
  }

  searchResult(): void {

  }
  restSearchFrom(e: MouseEvent): void {
    e.preventDefault();
    this.searchFrom.reset();
  }

  addTask(): void {
    this.isTaskModalVisible = true;
  }
  handleAdderCancel(): void {
    this.taskAdder?.reset();
    this.isTaskModalVisible = false;
  }
  handleAdderOk(): void {
    const submitData = this.taskAdder?.getData();
    if (submitData) {
      if (submitData.id) {
        this.updateTask(submitData);
      } else {
        this.createTask(submitData);
      }
    }

  }
  handleBriefCancel(): void {
    this.breidAdder?.reset();
    this.isTaskBriefVisible = false;
  }
  handleBriefOk(): void {
    const brief = this.breidAdder?.getValue();
    if (brief) {
      this.briefApi.create(brief).subscribe(
        respons => {
          this.msg.success('创建简报成功！');
          setTimeout(() => {
            this.handleBriefCancel();
          }, 500);
        },
        err => { }
      );
    }
  }
  completeTask(task: PeriodicTask): void {
    this.taskApi.setTaskCurrentStatus(task.id, ProcessStatus.done).subscribe(
      response => {
        this.msg.success('修改成功');
        this.fetchData();
      },
      err => {
        this.msg.error('修改错误');
        console.error(err);
      }
    );
  }
  handleBriefAdder(task: PeriodicTask): void {
    this.breidAdder?.setPeroidTaskId(task.id);
    this.isTaskBriefVisible = true;
  }
  handleEditTask(task: PeriodicTask): void {
    this.taskAdder?.setData(task);
    this.isTaskModalVisible = true;
    this.taskModalTitle = '编辑工作';
  }
  deleteTask(taskId: number): void {
    this.taskApi.delete([taskId]).subscribe(
      response => {
        this.msg.success('删除成功');
        this.fetchData();
      },
      err => {
        this.msg.error('删除错误');
        console.error(err);
      }
    );
  }
  navigateToDetail(taskId: number): void {
    this.router.navigateByUrl('/period/detail/' + taskId);
  }
  private fetchData(): void {
    this.isTableLoding = true;
    this.taskApi.listAll().subscribe(
      taskParamList => {
        this.isTableLoding = false;
        this.taskList = taskParamList.map(param => new PeriodicTask(param));
      },
      err => {
        this.isTableLoding = false;
        this.msg.error('获取工作列表错误');
        console.error(err);
       }
    );
  }
  private createTask(param: PeriodicTaskParam): void {
    this.taskApi.create(param).subscribe(
      task => {
        this.msg.success('创建工作成功！');
        setTimeout(() => {
          this.handleAdderCancel();
          this.fetchData();
        }, 500);
      },
      err => {
        this.msg.error('创建工作错误');
      }
    );
  }

  private updateTask(param: PeriodicTaskParam): void {
    this.taskApi.update(param.id, param).subscribe(
      task => {
        this.msg.success('编辑工作成功！');
        setTimeout(() => {
          this.handleAdderCancel();
          this.fetchData();
        }, 500);
      },
      err => {
        this.msg.error('编辑工作错误');
      }
    );
  }
}
